import {
  BadRequestException,
  Body,
  Controller,
  Get,
  Param,
  Post,
  Req,
  Res,
  Session,
} from '@nestjs/common';
import { AppService } from './app.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { LoginDto } from './common/dto/login.dto';
import { ApiObjOkResponse } from './common/decorator/response.decorator';
import { AuthDto } from './common/dto/auth.dto';
import { CaptchaService } from './common/utils/captcha/captcha.service';

@Controller()
@ApiTags('基础接口')
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly captchaService: CaptchaService,
  ) {}

  @ApiOperation({
    summary: '用户登录',
  })
  @ApiObjOkResponse(AuthDto)
  @Post('user/login')
  doLogin(@Body() form: LoginDto, @Session() session: any) {
    if (session.code === form.code || process.env.NODE_ENV == 'dev') {
      return this.appService.doLogin(form);
    } else {
      throw new BadRequestException('验证码错误！');
    }
  }

  @Get('captcha/:width/:height')
  @ApiOperation({
    summary: '获取验证码',
  })
  async getCode(
    @Res() res: any,
    @Req() req: any,
    @Param('height') height: number,
    @Param('width') width: number,
  ) {
    const svg = await this.captchaService.captcha(width, height);
    req.session.code = svg.text;
    res.type('image/svg+xml');
    res.send(svg.data);
  }
}
